﻿namespace D.Domain.SystemDomain.SysUserDomain.Entities
{
    /// <summary>
    /// 用户实体
    /// record更好的体现DDD充血模型，继承IAggregateRoot是表示用户实体当前为聚合根
    /// </summary>
    public class SysUserEntity : BaseEntity
    {
        /// <summary>
        /// 姓名 不可变，所以是init
        /// </summary>
        public string? Name { get; init; }

        /// <summary>
        /// 手机号，外部访问，内部修改
        /// </summary>
        public PhoneNumberVo PhoneNumber { get; private set; }

        /// <summary>
        /// 登录结果
        /// </summary>
        public SysAdminLoginFailEntity SysAdminLoginFail { get; private set; }

        /// <summary>
        /// 密码散列值
        /// </summary>
        private string? passWordMd5;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="phoneNumberVo"></param>
        public SysUserEntity(PhoneNumberVo phoneNumberVo)
        {
            this.Id = Guid.NewGuid();
            this.PhoneNumber = phoneNumberVo;
            this.SysAdminLoginFail = new SysAdminLoginFailEntity(this);
        }

        #region 针对实体所有状态改变的都需要抛出去一个事件


        /// <summary>
        /// 是否设置了密码
        /// </summary>
        /// <returns></returns>
        public bool HasPasswprd()
        {
            return !string.IsNullOrEmpty(passWordMd5);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="value"></param>
        public void ChangePwd(string value)
        {
            if (value.Length <= 6)
            {
                throw new ArgumentException("密码长度不能小于6");
            }
            passWordMd5 = MD5.Create(value).ToString();
        }

        /// <summary>
        /// 检测密码是否正确
        /// </summary>
        /// <param name="pwd"></param>
        public bool CheckPwd(string pwd)
        {
            return passWordMd5 == MD5.Create(pwd).ToString();
        }

        /// <summary>
        /// 修改手机号
        /// </summary>
        /// <param name="phoneNumberVo"></param>
        public void ChangePhoneNumer(PhoneNumberVo phoneNumberVo)
        {
            PhoneNumber = phoneNumberVo;
        }
        #endregion
    }
}
